<template>
  <view class="container">
    <!-- 弹框遮罩层 -->
    <view v-if="showDialog" class="overlay" @click="closeDialog"></view>

    <!-- 弹框 -->
    <view v-if="showDialog" class="dialog">
      <view class="dialog-content">
        <view class="dialog-item">
          <input type="text" v-model="nickname" placeholder="请先登陆" />
        </view>
        <view class="dialog-item">
          <button @click="submit">确认</button>
          <button @click="closeDialog">取消</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, defineProps, defineEmits, watch } from 'vue'

// 定义 prop 类型
interface ChooseAvatarProps {
  isDialogVisible: boolean
}

// 定义事件参数类型
interface AvatarData {
  avatar: string
  nickname: string
}

// 接收父组件传递的 prop 控制弹框显示
const props = defineProps<ChooseAvatarProps>()

// 发送数据的事件
const emit = defineEmits<{
  (event: 'updateData', data: AvatarData): void
}>()

// 头像和昵称的状态
const avatar = ref<string>('')
const nickname = ref<string>('')

// 控制弹框显示的状态
const showDialog = ref<boolean>(props.isDialogVisible)

// 监听 prop 值的变化
watch(
  () => props.isDialogVisible,
  (newValue) => {
    console.log('vserr', newValue)
    showDialog.value = newValue
  }
)

// 打开弹框
const openDialog = () => {
  showDialog.value = true
}

// 关闭弹框
const closeDialog = () => {
  showDialog.value = false
}

// 选择头像
const chooseAvatar = (e: any) => {
  const { avatarUrl } = e.detail
  console.log(avatarUrl, '-e-e-')
  avatar.value = avatarUrl
}

// 提交数据
const submit = () => {
  const data: AvatarData = {
    avatar: avatar.value,
    nickname: nickname.value,
  }

  // 通过 emit 传递数据给父组件
  emit('updateData', data)

  // 关闭弹框
  closeDialog()
}
</script>

<style lang="scss">
.container {
  padding: 20px;
}

.profile {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.nickname {
  font-size: 16px;
}

.open-dialog-btn {
  padding: 10px;
  background-color: #007aff;
  color: white;
  border-radius: 5px;
}

.overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
}

.dialog {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background: white;
  border-radius: 8px;
  padding: 20px;
  width: 80%;
  max-width: 400px;
}

.dialog-content {
  display: flex;
  flex-direction: column;
}

.dialog-item {
  margin-bottom: 20px;
}

.dialog-item input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.dialog-item button {
  width: 100%;
  padding: 10px;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.dialog-item button:nth-child(2) {
  background-color: #ccc;
}
</style>
